package com.food.restaurantpro.adapters;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.food.restaurantpro.R;
import com.food.restaurantpro.imageloader.ImageLoader;
import com.food.restaurantpro.objects.DishCategory;

public class MenuGridViewAdapter extends ArrayAdapter<DishCategory> {

	private Context mContext;
	private ImageLoader imageLoader;
	private ArrayList<DishCategory> mDishCategoryList;
	private LayoutInflater inflater;

	public MenuGridViewAdapter(Context context,
			ArrayList<DishCategory> dishCategoryList) {
		super(context, R.layout.gv_menu_item, R.id.menu_item_name,
				dishCategoryList);
		this.mContext = context;
		this.mDishCategoryList = dishCategoryList;
		inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(mContext, R.drawable.image0, 1);
	}

	@Override
	public int getCount() {
		return mDishCategoryList.size();
	}

	@Override
	public DishCategory getItem(int position) {
		return mDishCategoryList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View gridView;
		ViewHolder viewHolder = null;
		if (convertView == null) {
			gridView = inflater.inflate(R.layout.gv_menu_item, null);
			viewHolder = new ViewHolder();
			viewHolder.textName = (TextView) gridView
					.findViewById(R.id.menu_item_name);
			viewHolder.imageView = (ImageView) gridView
					.findViewById(R.id.menu_item_image);
			gridView.setTag(viewHolder);
		} else {
			gridView = convertView;
			viewHolder = (ViewHolder) gridView.getTag();
		}
		viewHolder.textName.setText(mDishCategoryList.get(position)
				.getDishCategoryName());
		imageLoader.displayImage(mDishCategoryList.get(position)
				.getDishCategoryImage(), viewHolder.imageView);
		viewHolder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
		return gridView;
	}

	public class ViewHolder {
		public TextView textName;
		public ImageView imageView;
	}

	public void clearMemoryCache() {
		if (mDishCategoryList != null) {
			mDishCategoryList.clear();
			mDishCategoryList = null;
		}
		inflater = null;
		imageLoader.clearMemoryCache();
	}
}
